<?php

/**
 * @package Bike
 * @subpackage Parser
 */

/**
 * Bike BO parser
 * @author Chrome
 * @package Bike
 * @subpackage Parser
 */
class Bike_Parser_Bike implements Bike_Parser_IParser {

	/**
	 * Path to templates
	 * @var string
	 */
	protected $templatePath = '';
	
	/**
	 * Template data
	 * @var array
	 */
	protected $templateData = array();
	
	/**
	 * Current template for parse
	 * @var string
	 */
	protected $template = '';
	
	/**
	 * Controller for template
	 * @var string
	 */
	protected $controller = '';

	/**
	 * Constructor
	 */
	public function __construct(){

	}

	/* (non-PHPdoc)
	 * @see Bike_Parser_IParser::setTemplatePath()
	 */
	public function setTemplatePath($path){
		$this->templatePath = $path;
		return true;
	}
	
	/* (non-PHPdoc)
	 * @see Bike_Parser_IParser::getTemplatePath()
	 */
	public function getTemplatePath(){
		return $this->templatePath;
	}

	/* (non-PHPdoc)
	 * @see Bike_Parser_IParser::setTemplate()
	 */
	public function setTemplate($pathToTemplate){
		$controller = substr($pathToTemplate, 0, -3) . 'php';
		if(!file_exists($this->templatePath . $pathToTemplate) || !file_exists($this->templatePath . $controller)){
			throw new Bike_Parser_Exception('Template file not found', Bike_Parser_Exception::TEMPLATE_NOT_FOUND);
		}
		$this->template = $this->templatePath . $pathToTemplate;
		$this->controller = $this->templatePath . $controller;
		return true;
	}

	/* (non-PHPdoc)
	 * @see Bike_Parser_IParser::set()
	 */
	public function set($placeHolder, $data){
		$this->templateData[$placeHolder] = $data;
		return true;
	}
	
	/**
	 * Get previously setted value
	 * @param string $placeHolder
	 * @return mixed
	 */
	public function get($placeHolder){
		if(!empty($this->templateData[$placeHolder])){
			return $this->templateData[$placeHolder];
		}
		return false;
	}

	/* (non-PHPdoc)
	 * @see Bike_Parser_IParser::processTemplate()
	 */
	public function processTemplate(){
		require_once($this->controller);
		$templateContent = file_get_contents($this->template);
		$search = $replacement = array();
		foreach($this->templateData as $key=>$value){
			$search[] = '{{' . $key . '}}';
			$replacement[] = $value;
		}
		if(!empty($search)){
			$templateContent = str_replace($search, $replacement, $templateContent);
		}
		return $templateContent;
	}
}
